<template>
  <div class="qualification-management">
    <div class="container">
      <div class="header">
        <h1>资质信息管理系统</h1>
        <div>
          <el-button type="primary" icon="Plus" @click="addQualification">新增资质</el-button>
          <el-button icon="Refresh" @click="refreshData">刷新</el-button>
        </div>
      </div>

      <div class="search-bar">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input v-model="searchForm.qualification_number" placeholder="资质编号" clearable>
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select v-model="searchForm.qualification_type" placeholder="资质类型" clearable>
              <el-option label="建筑施工安全员" value="建筑施工安全员"></el-option>
              <el-option label="建筑工程施工总承包一级" value="建筑工程施工总承包一级"></el-option>
              <el-option label="注册造价工程师" value="注册造价工程师"></el-option>
              <el-option label="安全生产许可证" value="安全生产许可证"></el-option>
              <el-option label="注册会计师" value="注册会计师"></el-option>
              <el-option label="法律职业资格证" value="法律职业资格证"></el-option>
              <el-option label="医疗器械经营许可证" value="医疗器械经营许可证"></el-option>
              <el-option label="执业医师资格证" value="执业医师资格证"></el-option>
              <el-option label="食品经营许可证" value="食品经营许可证"></el-option>
              <el-option label="教师资格证" value="教师资格证"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select v-model="searchForm.status" placeholder="状态" clearable>
              <el-option label="有效" value="有效"></el-option>
              <el-option label="吊销" value="吊销"></el-option>
              <el-option label="即将过期" value="即将过期"></el-option>
              <el-option label="已过期" value="已过期"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" icon="Search" @click="searchQualifications">搜索</el-button>
            <el-button icon="RefreshRight" @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <div v-loading="loading">
        <div class="card-container">
          <!-- 资质卡片 -->
          <div v-for="(item, index) in currentPageData" :key="index" class="info-card">
            <div class="card-header">
              <span>资质信息 #{{ item.qualification_number }}</span>
              <span :class="['status-badge', `status-${getStatusClass(item.status)}`]">
                {{ item.status }}
                <span v-if="isExpiring(item.expiry_date)" class="expiry-warning">
                  <el-icon><Warning /></el-icon>
                  {{ daysUntilExpiry(item.expiry_date) }}天后过期
                </span>
              </span>
            </div>
            <div class="card-body">
              <div class="form-row">
                <div class="form-label">所有者类型:</div>
                <div class="form-content">{{ item.owner_type }}</div>
              </div>
              <div class="form-row">
                <div class="form-label">所有者ID:</div>
                <div class="form-content">{{ item.owner_id }}</div>
              </div>
              <div class="form-row">
                <div class="form-label">资质类型:</div>
                <div class="form-content">{{ item.qualification_type }}</div>
              </div>
              <div class="form-row">
                <div class="form-label">资质编号:</div>
                <div class="form-content">{{ item.qualification_number }}</div>
              </div>
              <div class="form-row">
                <div class="form-label">发证机关:</div>
                <div class="form-content">{{ item.issuing_authority }}</div>
              </div>
              <div class="form-row">
                <div class="form-label">发证日期:</div>
                <div class="form-content">{{ formatDate(item.issue_date) }}</div>
              </div>
              <div class="form-row">
                <div class="form-label">生效日期:</div>
                <div class="form-content">{{ formatDate(item.effective_date) }}</div>
              </div>
              <div class="form-row">
                <div class="form-label">失效日期:</div>
                <div class="form-content">{{ formatDate(item.expiry_date) }}</div>
              </div>
              <div class="form-row">
                <div class="form-label">备注:</div>
                <div class="form-content">{{ item.remark || '无' }}</div>
              </div>
            </div>
            <div class="action-buttons">
              <el-button type="primary" plain icon="Edit" @click="editQualification(item)">编辑</el-button>
              <el-button type="success" plain icon="Document" @click="viewDetail(item)">查看详情</el-button>
              <el-button type="danger" plain icon="Delete" @click="deleteQualification(item)">删除</el-button>
            </div>
          </div>

          <!-- 空状态卡片 -->
          <div v-if="filteredQualifications.length === 0 && !loading" class="empty-card">
            <el-icon :size="60" color="#C0C4CC"><Plus /></el-icon>
            <p>暂无资质信息</p>
            <el-button type="primary" icon="Plus" style="margin-top: 20px;" @click="addQualification">新增资质</el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container" v-if="filteredQualifications.length > 0">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :total="filteredQualifications.length"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { getSupplierInfo } from './supplier.js';
import { ref, computed, onMounted } from 'vue';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
const router = useRouter();
// 搜索表单
const searchForm = ref({
  qualification_number: '',
  qualification_type: '',
  status: ''
});

// 资质数据
const qualifications = ref([]);
const filteredQualifications = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const totalRecords = ref(0); // 添加总记录数变量

// 计算当前页显示的数据
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredQualifications.value.slice(start, end);
});

// 格式化日期
const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD');
};

// 计算距离过期的天数
const daysUntilExpiry = (expiryDate) => {
  const today = dayjs();
  const expiry = dayjs(expiryDate);
  return expiry.diff(today, 'day');
};

// 判断是否即将过期（30天内）
const isExpiring = (expiryDate) => {
  const days = daysUntilExpiry(expiryDate);
  return days > 0 && days <= 30;
};

// 获取状态对应的CSS类
const getStatusClass = (status) => {
  const statusMap = {
    '有效': 'active',
    '吊销': 'revoked',
    '即将过期': 'expiring',
    '已过期': 'expired'
  };
  return statusMap[status] || 'unknown';
};

// 调用接口获取资质数据
const fetchQualifications = async () => {
  try {
    loading.value = true;
    const queryParams = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };
    const response = await getSupplierInfo(queryParams);
    
    if (response.code === 200) {
      // 将接口返回的数据映射到前端格式
      qualifications.value = response.data.records.map(item => ({
        id: item.id,
        owner_type: item.ownerType,
        owner_id: item.ownerId,
        qualification_type: item.qualificationType,
        qualification_number: item.qualificationNumber,
        issuing_authority: item.issuingAuthority,
        issue_date: item.issueDate,
        effective_date: item.effectiveDate,
        expiry_date: item.expiryDate,
        status: item.status,
        remark: item.remark
      }));
      
      // 动态计算状态（有效 → 即将过期/已过期）
      qualifications.value = qualifications.value.map(item => {
        if (item.status === '有效') {
          const today = dayjs();
          const expiry = dayjs(item.expiry_date);
          const days = expiry.diff(today, 'day');
          
          if (days < 0) {
            item.status = '已过期';
          } else if (days <= 30) {
            item.status = '即将过期';
          }
        }
        return item;
      });
      
      filteredQualifications.value = [...qualifications.value];
      totalRecords.value = response.data.total;
    } else {
      console.error('获取数据失败:', response.msg);
      ElMessage.error('获取数据失败: ' + response.msg);
    }
  } catch (error) {
    console.error('请求出错:', error);
    ElMessage.error('请求出错: ' + error.message);
  } finally {
    loading.value = false;
  }
};

// 搜索资质 - 精确匹配
const searchQualifications = () => {
  loading.value = true;
  
  // 使用setTimeout模拟API请求延迟
  setTimeout(() => {
    if (!searchForm.value.qualification_number && 
        !searchForm.value.qualification_type && 
        !searchForm.value.status) {
      // 所有搜索条件为空时显示全部数据
      filteredQualifications.value = [...qualifications.value];
    } else {
      filteredQualifications.value = qualifications.value.filter(item => {
        // 精确匹配资质编号
        const matchesNumber = searchForm.value.qualification_number 
          ? item.qualification_number === searchForm.value.qualification_number
          : true;
          
        // 精确匹配资质类型
        const matchesType = searchForm.value.qualification_type 
          ? item.qualification_type === searchForm.value.qualification_type
          : true;
          
        // 精确匹配状态
        const matchesStatus = searchForm.value.status 
          ? item.status === searchForm.value.status
          : true;
          
        return matchesNumber && matchesType && matchesStatus;
      });
    }
    
    currentPage.value = 1;
    loading.value = false;
  }, 500);
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    qualification_number: '',
    qualification_type: '',
    status: ''
  };
  filteredQualifications.value = [...qualifications.value];
  currentPage.value = 1;
};

// 刷新数据
const refreshData = () => {
  fetchQualifications();
};

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchQualifications(); // 重新获取数据
};

// 当前页改变
const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchQualifications(); // 重新获取数据
};

// 新增资质
const addQualification = () => {
    router.push({ 
    path: '/qualification/add'
  });
};

// 编辑资质
const editQualification = (item) => {
  ElMessage.info(`编辑资质: ${item.qualification_number}`);
};

// 查看详情
const viewDetail = (item) => {
  ElMessage.info(`查看资质详情: ${item.qualification_number}`);
};

// 删除资质
const deleteQualification = (item) => {
  ElMessageBox.confirm(
    `确定要删除资质 "${item.qualification_number}" 吗？此操作不可恢复。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 这里应该调用删除API
    // 删除成功后刷新数据
    fetchQualifications();
    ElMessage.success('资质删除成功');
  }).catch(() => {
    // 用户取消操作
  });
};

onMounted(() => {
  fetchQualifications();
});
</script>

<style scoped>
.qualification-management {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.container {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  padding: 25px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #1f2d3d;
}

.search-bar {
  margin-bottom: 25px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
}

.el-row {
  margin-bottom: -20px;
}

.el-col {
  margin-bottom: 20px;
}

.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(420px, 1fr));
  gap: 25px;
  margin-bottom: 30px;
}

.info-card {
  border: 1px solid #e4e7ed;
  border-radius: 10px;
  background: #fff;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
}

.info-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8fafc;
  border-bottom: 1px solid #ebeef5;
}

.card-header span:first-child {
  font-weight: 600;
  color: #1f2d3d;
}

.status-badge {
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background-color: #e1f3d8;
  color: #67c23a;
}

.status-expiring {
  background-color: #faecd8;
  color: #e6a23c;
}

.status-expired {
  background-color: #fde2e2;
  color: #f56c6c;
}

.status-revoked {
  background-color: #f0f0f0;
  color: #909399;
}

.card-body {
  padding: 20px;
}

.form-row {
  display: flex;
  margin-bottom: 14px;
  font-size: 14px;
}

.form-label {
  width: 100px;
  color: #909399;
  flex-shrink: 0;
}

.form-content {
  flex: 1;
  color: #606266;
  word-break: break-word;
}

.action-buttons {
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  background: #f8fafc;
  border-top: 1px solid #ebeef5;
}

.empty-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
  background-color: #f5f7fa;
  color: #909399;
  grid-column: 1 / -1;
}

.empty-card p {
  margin: 15px 0;
  font-size: 16px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 25px;
}

.expiry-warning {
  display: inline-flex;
  align-items: center;
  padding: 2px 8px;
  border-radius: 4px;
  background: #fdf6ec;
  color: #e6a23c;
  font-size: 12px;
  margin-left: 8px;
}

.expiry-warning i {
  margin-right: 4px;
}

@media (max-width: 992px) {
  .card-container {
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header > div {
    margin-top: 15px;
    width: 100%;
  }
  
  .search-bar .el-col {
    width: 100%;
    flex: 0 0 100%;
    max-width: 100%;
  }
  
  .card-container {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .action-buttons .el-button {
    flex: 1;
    min-width: 120px;
  }
}
</style>